package com.blazemina.mina.acceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.blazegame.logging.Logger;
import com.blazegame.logging.LoggerFactory;
import com.blazemina.config.BlazeminaConfig;
import com.blazemina.config.BlazeminaConfigManager;
import com.blazemina.config.IdleTime;
import com.blazemina.config.IoService;
import com.blazemina.config.ServiceAcceptor;
import com.blazemina.config.ServiceFilter;
import com.blazemina.config.SocketOption;
import com.blazemina.util.ClassUtils;

/**
 * 服务器入口类
 * 
 * @author JackChu
 * @version 1.0.0 2012-1-11 下午8:05:30
 */
public class AbstractAcceptor {

	private static final Logger log = LoggerFactory
			.getLogger(AbstractAcceptor.class);

	/**
	 * 用户自定义初始化
	 */
	public void init(){
		
	}

	private synchronized void initConfig() {
		BlazeminaConfigManager.getManager().init();
	}

	/**
	 * 服务器的初始化
	 */
	private void initAcceptor() {
		initConfig();
		init();
	}
	
	private IoAcceptor acceptor;

	/**
	 * 服务器启动
	 */
	public void start() {
		initAcceptor();

		BlazeminaConfig blazeminaConfig = BlazeminaConfigManager.getManager()
				.getBlazeminaConfig();
		IoService ioService = blazeminaConfig.getIoService();
		int socketThreads = ioService.getSocketThreads();

		acceptor = new NioSocketAcceptor(socketThreads);

		SocketSessionConfig socketSessionConfig = (SocketSessionConfig) acceptor
				.getSessionConfig();

		SocketOption socketOption = blazeminaConfig.getSocketOption();
		int receiveBufferSize = socketOption.getSocketReceiveBuffer();
		if (receiveBufferSize != 0) {
			socketSessionConfig.setReceiveBufferSize(receiveBufferSize);
		}
		int sendBufferSize = socketOption.getSocketSendBuffer();
		if (sendBufferSize != 0) {
			socketSessionConfig.setSendBufferSize(sendBufferSize);
		}
		socketSessionConfig.setKeepAlive(socketOption.isKeepAlive());
		socketSessionConfig.setTcpNoDelay(socketOption.isTcpNoDelay());
		
		IdleTime idleTime = socketOption.getIdleTime();
		IdleStatus idleStatus = IdleStatus.BOTH_IDLE;
		if(idleTime != null&&idleTime.getState() != IdleTime.STATE_NOT_IDLE){
			switch (idleTime.getState()) {
			case IdleTime.STATE_BOTH_IDLE:
				idleStatus = IdleStatus.BOTH_IDLE;
				break;
			case IdleTime.STATE_READ_IDLE:
				idleStatus = IdleStatus.READER_IDLE;
				break;
			case IdleTime.STATE_WRITE_IDLE:
				idleStatus = IdleStatus.WRITER_IDLE;
				break;
			default:
				break;
			}
			socketSessionConfig.setIdleTime(idleStatus, idleTime.getTimeoutSeconds());
		}

		log.debug("Start Initialize IoFilter");

		ServiceAcceptor serviceAcceptor = ioService.getServiceAcceptor();
		Map<String, ServiceFilter> filters = serviceAcceptor
				.getFilters();
		for (Entry<String, ServiceFilter> filter : filters.entrySet()) {
			String filterName = filter.getKey();
			ServiceFilter serviceFilter = filter.getValue();
			if(ServiceFilter.TYPE_CODEC_FACTORY.equals(serviceFilter.getType())){
				ProtocolCodecFactory protocolCodecFactory = null;
				try {
					protocolCodecFactory = (ProtocolCodecFactory)ClassUtils.applicationInstance(serviceFilter.getClassName());
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				acceptor.getFilterChain().addLast(filterName, new ProtocolCodecFilter(protocolCodecFactory));
				log.debug("add filter,type is codecFactory. name:#1, class:#2", filterName, serviceFilter.getClassName());
			}else{
				IoFilter ioFilter = serviceFilter.getIoFilter();
				acceptor.getFilterChain().addLast(filterName, ioFilter);
				log.debug("add filter name:#1, class:#2", filterName, serviceFilter.getClassName());
			}
		}

		log.debug("Start Initialize SessionHandle");
		acceptor.setHandler(serviceAcceptor.getServerHandler());

		bind(acceptor,ioService);
	}

	private void bind(IoAcceptor acceptor,IoService ioService) {
		String host = ioService.getServiceAcceptor().getLocalHost();
		int port = ioService.getServiceAcceptor().getLocalPort();
		SocketAddress address = new InetSocketAddress(port);
		if(host!=null){
			address = new InetSocketAddress(host, port);
		}
		
		try {
			acceptor.bind(address);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		log.debug("Acceptor has Started,host:#1,port:#2",host==null?"localhost":host,""+port);


	}
	
	
	public void stop() {
		if(acceptor!=null){
			acceptor.dispose();
		}
		log.debug("Acceptor has stoped!!");
	}

}
